<?php

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );

class RcbaseModelMotorset extends JModel
{
	function getMotor($id=1)
	{
		$db =& JFactory::getDBO();
		$query = 'SELECT * FROM #__rcbase_motorlist WHERE id = '.$id;
		$db->setQuery( $query );
		$res = $db->loadAssoc();

		return $res;
	}

	function getTest($id=1)
	{
		$db =& JFactory::getDBO();
		$query = 'SELECT * FROM #__rcbase_motortest WHERE id = '.$id;
		$db->setQuery( $query );
		$res = $db->loadAssoc();

		return $res;
	}

	function saveSet()
	{
		$db           =& JFactory::getDBO();
		$user         =& JFactory::getUser();
		$motor_id     = JRequest::getInt('motor_id');
		$model_name   = JRequest::getVar('model_name');
		$model_type   = JRequest::getVar('model_type');
		$model_weight = JRequest::getVar('model_weight');
		$prop_type    = JRequest::getVar('prop_type');
		$prop_d       = JRequest::getVar('prop_d');
		$prop_h       = JRequest::getVar('prop_h');
		$cells        = JRequest::getVar('cells');
		$esc_current  = JRequest::getVar('esc_current');
		for ($i=0;$i<=9;$i++)
		{
			if ($model_name[$i] and $model_type[$i] and $model_weight[$i] and $prop_d[$i] and $prop_h[$i]and $cells[$i] and $esc_current[$i])
			{
				$query = "
					INSERT INTO #__rcbase_motorset SET
						motor_id = ".$db->quote($motor_id).",
						user_id = ".$db->quote($user->id).",
						model_name = ".$db->quote($model_name[$i]).",
						model_type = ".$db->quote($model_type[$i]).",
						model_weight = ".$db->quote($model_weight[$i]).",
						prop_type = ".$db->quote($prop_type[$i]).",
						prop_d = ".$db->quote($prop_d[$i]).",
						prop_h = ".$db->quote($prop_h[$i]).",
						cells = ".$db->quote($cells[$i]).",
						esc_current = ".$db->quote($esc_current[$i])."
				";
				#die(print_r($query));
				$db->setQuery( $query );
				$db->query();
			}
		}
	}

	function setMotorSetRate($id, $voit){
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();
		# Гость не может голосовать по любому!
		if ($user->guest) return 'guest';
		$test = $this->getTest($id);
		# Проверяем что пользователь еще не голосовал
		if (strpos($test['rate_up'].'|'.$test['rate_down'], $user->id) === false){
			if ($voit == 'up'){ # Голосим ЗА!
				$query = "
					UPDATE #__rcbase_motorset
					SET rate_up = IF(rate_up != '',CONCAT(rate_up, '|".$user->id."'),'".$user->id."')
					WHERE id = ".$id."
				";
				$db->setQuery( $query );
				$db->query();
				return 'up';
			} else { # Голосим ПРОТИВ!
				$query = "
					UPDATE #__rcbase_motorset
					SET rate_down = IF(rate_down != '',CONCAT(rate_up, '|".$user->id."'),'".$user->id."')
					WHERE id = ".$id."
				";
				$db->setQuery( $query );
				$db->query();
				return 'down';
			}
		} else { # иначе возвращаем статус "Уже есть"
			return 'exist';
		}
	}

}